﻿import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableWithoutFeedback,
    Image,
    ToastAndroid,
    TextInput,
    NativeModules,
    AsyncStorage,
    Alert,
    TouchableOpacity,
    DeviceEventEmitter,
    Button,
    ScrollView
} from 'react-native';


import NavigatorBar from '../../common/NavigationBar';

import Alipay from '../../common/Native/Alipay.js';

import { saveOrder } from '../../api/payService';

import sha256 from 'sha256';

const Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');


import { queryExueyunMoney } from '../../api/my';

import EditView from '../../common/EditView'

import { Toast, Overlay, Label } from 'teaset';



class PayScreen extends Component {



    constructor() {
        super();



        this.checkIconImgs = {
            "checked": require('../../assets/imgs/selectActive.png'),
            "unchecked": require('../../assets/imgs/unchecked.png')
        };

        var that = this;

        payCourseInfoStr = AsyncStorage.getItem('payCourseInfo').then((res) => {
            global.log(res, "AsyncStorage.getItem=>payCourseInfo");
            this.setState({
                payCourseInfo: JSON.parse(res)
            });
        });


        var payCourseInfoStr = '{"BASICINFO":{"COURSE_NAME":"","STOP_TIME":"","TEACHER_NAME":"","TOTLE_MONEY":""},"LISTCOURSE":[{"COURSE_TYPE":"0","COURSE_ID":"","MONEY":"","COURSE_NAME":""}]}';

        var payCourseInfo = JSON.parse(payCourseInfoStr);

        this.state = {
            PAY_TYPE: 'account', // account,alipay,weixin,
            text: '478880002092433408', //课程id调
            PASSWORD: '',
            payCourseInfo: payCourseInfo,
            btnText: "确认支付",
            remainderSum: 0,  //e学云余额
            IsPassWordSetted: false
        };

        global.log(this.state, "===========ddddddddddddddddd=============");


        let json = {
            "PAY_USER_ID": global.ECourseConstant.userInfo.uuid
        }
        queryExueyunMoney(json).then(res => {
            global.log(res, "============queryExueyunMoney=============");
            var arr = res.split(',');
            this.setState({
                remainderSum: arr[0],
                IsPassWordSetted: arr[1] == "0" ? true : false
            });



        });

    }

    componentWillMount() {
        var that = this;
        DeviceEventEmitter.addListener('PassWordSetted_NativeEmitter', function () {

            Toast.show({
                text: '密码设置成功,请重新支付',
                position: 'bottom',
                duration: 2000,
            });

            that.setState({
                IsPassWordSetted: true
            });
        });



        DeviceEventEmitter.addListener('PayPassWordSetted_NativeEmitter', function (pwd) {
            that.setState({
                PASSWORD: pwd
            }, function () {
                that._onPressSubmit();
            });
        });


    }


    // 渲染按钮
    renderLeftButton(image) {
        return <TouchableOpacity
            style={[global.CommonStyleSheet.NavLeftButton]}
            onPress={() => {
                this.props.navigation.goBack();
            }}>
            <Image
                style={{ width: 34, height: 34 }}
                source={image} />
        </TouchableOpacity>;
    }

    _onPressPaySelect(type) {
        var msg = "hello";
        this.setState({
            PAY_TYPE: type
        });
    }

    MoreText(text, MaxNum) {
        MaxNum = MaxNum || 10;
        if (text) {
            if (text.length > MaxNum) {
                return (
                    text.substring(0, MaxNum) + '...'
                )
            } else {
                return (
                    text
                )
            }
        }
    }

    ensureCallback() {

        if (this.state.PASSWORD.length == 0) {
            Toast.show({
                text: '请输入密码',
                position: 'bottom',
                duration: 2000,
            });
            return false;
        }

        this._onPressSubmit();

    }




    async onPressSubmit() {

        // console.log("============345654===============");


        // this.props.navigation.navigate("PaySuccessScreen", {

        //     payCourseInfo: this.state.payCourseInfo

        // });
        // return false;


        if (this.state.btnText == "支付中,请稍等") {
            return false;
        }

        if (this.state.PAY_TYPE == "account") {
            this._onPressSubmitExue();
        } else {
            this._onPressSubmit();
        }

    }


    async _onPressSubmitExue() {

        var that = this;

        //判断有密码没
        if (this.state.IsPassWordSetted) {
            var totalMoney = that.state.payCourseInfo.BASICINFO.TOTLE_MONEY
            NativeModules.BaseBridge.ejectPayPanel('' + totalMoney);
        } else {

            //跳转密码设置页
            let overlayView = (
                <Overlay.View
                    style={{ alignItems: 'center', justifyContent: 'center' }}
                    modal={true}
                    overlayOpacity={0.5}
                    ref={v => this.overlayView = v}
                >
                    <View style={{ backgroundColor: 'white', width: 250, height: 120, borderColor: '#eee', borderWidth: 1, borderRadius: 15, alignItems: 'center' }}>
                        <View style={[styles.center, { width: 200, height: 70 }]}>
                            <Text style={{ color: '#999' }}>帐号未设置密码</Text>
                        </View>
                        <View style={styles.buttonContainer}>
                            <TouchableOpacity
                                activeOpacity={0.85}
                                style={[styles.center, { flex: 10 }]}
                                onPress={() => {
                                    this.overlayView && this.overlayView.close();
                                    NativeModules.BaseBridge.setPayPassword();
                                }}
                            >
                                <Text style={{ fontSize: 16, color: 'black' }}>去设置</Text>
                            </TouchableOpacity>

                        </View>

                    </View>
                </Overlay.View>
            );
            Overlay.show(overlayView);


        }
    }

    async _onPressSubmit() {

        var that = this;

        var courseList = this.state.payCourseInfo.LISTCOURSE.map(function (item, i) {
            return {
                COURSE_TYPE: item.COURSE_TYPE,
                COURSE_ID: item.COURSE_ID,
                MONEY: item.MONEY
            }
        });

        global.log(courseList, "=======courseList======");
        var orderInfo = {
            "PAY_USER_ID": global.ECourseConstant.userInfo.uuid,
            "PAY_USER_NAME": global.ECourseConstant.userInfo.userName || '缺失',
            "PAY_TYPE": this.state.PAY_TYPE,
            "PASSWORD": this.state.PASSWORD + "",
            "LISTCOURSE": courseList
        }

        global.log(orderInfo);


        this.setState({
            btnText: "支付中,请稍等"
        })



        saveOrder(orderInfo).then((res) => {

            setTimeout(() => {
                this.setState({
                    btnText: "确认支付"
                })
            }, 1000);


            if (that.state.PAY_TYPE == "account") {
                that.props.navigation.navigate("PaySuccessScreen", {

                    payCourseInfo: this.state.payCourseInfo

                });
            } else if (that.state.PAY_TYPE == "alipay") {
                var orderId = "";
                //orderId="alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2017112800229202&biz_content=%7B%22body%22%3A%22e%E8%AF%BE%E8%A7%86%E9%A2%91%22%2C%22enable_pay_channels%22%3A%22balance%2CmoneyFund%2CdebitCardExpress%22%2C%22out_trade_no%22%3A%220808150153-1291%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22e%E8%AF%BE%E8%A7%86%E9%A2%91%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.1%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F192.168.121.21%3A8080%2Fexue-exueyun-api-web%2Feke%2Fcourse%2FzfbReturn%2FcourseReturn%2F476767009678426112&sign=CGBcqkJLfACGD5XhEKndth9iyhrwGi05awdn7HbZBxSECRW%2FPRESk5O%2Bu%2FDPg4JRQo%2FlwnOtj2wrajcS7GcHHaeSthP%2Fb1yELo6mIGcffskKDMK7UACrfJU05%2Bn4BBlQycf1SEJaRb6a6DNM6AFBvnWmcghgtfPwfhpWumb5mpX%2BVmqN7nhvkIDS9PTy0f%2FxgzVFxDbthG7ecvFnkcRBE%2FVAb84bb1UUYGTC5oREuaV5PKueTyUzvmn4jP%2Btssd3sutYSAiSdA4N60yd%2F0wzlBB8rPiNKNBzB7Lho5SPFKLFnimgYIxuHXwQaFYEKLKaBtpqSiTmlpDNYA5wtbpPfA%3D%3D&sign_type=RSA2&timestamp=2018-08-08+15%3A01%3A53&version=1.0";
                orderId = res[0].payInfo;
                return Alipay.payV2(orderId); // 调起支付宝，发起支付
            } else if (that.state.PAY_TYPE == "weixin") {
                var orderId = "";
                orderId = res[0].payInfo;
                return NativeModules.Wxpay.pay(orderId); // 调起支付宝，发起支付
            }


        }).then((ResultStatus) => {


            global.log("回调总入口" + ResultStatus);

            if (that.state.PAY_TYPE == "alipay") {

                if (ResultStatus == "9000") {
                    that.props.navigation.navigate("PaySuccessScreen", {
                        payCourseInfo: this.state.payCourseInfo
                    });
                }
                else if (ResultStatus == "6001") {
                    Toast.show({
                        text: '支付失败',
                        position: 'bottom',
                        duration: 2000,
                    });
                } else {
                    Toast.show({
                        text: '支付错误,' + "返回状态码:" + ResultStatu,
                        position: 'bottom',
                        duration: 2000,
                    });
                }

            } else if (that.state.PAY_TYPE == "weixin") {

                global.log("回调微信" + ResultStatus);

                if (ResultStatus == "0") {
                    that.props.navigation.navigate("PaySuccessScreen", {
                        payCourseInfo: this.state.payCourseInfo
                    });
                } else if (ResultStatus == "-1") {
                    Toast.show({
                        text: '支付失败',
                        position: 'bottom',
                        duration: 2000,
                    });
                } else if (ResultStatus == "-2" || ResultStatus == -2) {
                    Toast.show({
                        text: '取消支付',
                        position: 'bottom',
                        duration: 2000,
                    });
                } else {
                    Toast.show({
                        text: '支付错误,' + "返回状态码:" + ResultStatus,
                        position: 'bottom',
                        duration: 2000,
                    });
                }
            }


        }).catch((result) => {
            this.setState({
                btnText: "确认支付"
            })
            Toast.message(result.RESULT_DESC)
        });
    }

    render() {
        return (
            <View style={[styles.mainContainer]}>

                <NavigatorBar
                    title={'确认订单'}
                    style={styles.navigatorBar}
                    leftButton={this.renderLeftButton(require('../../assets/imgs/back.png'))}
                />


                <ScrollView
                    showsVerticalScrollIndicator={false}
                >

                    <View style={[styles.card]}>


                        <View style={[styles.order_card]}>



                            {
                                this.state.payCourseInfo.LISTCOURSE.map((course, i) => {
                                    return (
                                        <View style={[styles.order_card_body]} key={i}>
                                            <View style={[styles.order_card_body_left]}>
                                                <Text style={[styles.order_title_wrap]}>{this.MoreText(course.COURSE_NAME, 14)}</Text>
                                                <Text style={[styles.order_teacher_wrap]}>授课老师: {this.state.payCourseInfo.BASICINFO.TEACHER_NAME}</Text>
                                                {/* <Text style={[styles.order_buy_limit_time]}>报名截止时间:{this.state.payCourseInfo.BASICINFO.STOP_TIME}</Text> */}
                                            </View>
                                            <View style={[styles.order_card_body_right]}>
                                                <Text style={[styles.order_title_wrap]}>¥{course.MONEY}</Text>
                                            </View>
                                        </View>
                                    )
                                })
                            }


                            <View style={[styles.order_card_footer]}>
                                <View style={{ flexDirection: 'row' }}>
                                    <Text style={[styles.color_666]}>需支付:</Text>
                                    <Text style={[styles.color_333, styles.amount]}>¥{this.state.payCourseInfo.BASICINFO.TOTLE_MONEY}</Text>
                                </View>
                            </View >


                        </View >
                    </View >

                    <TouchableWithoutFeedback onPress={() => this._onPressPaySelect('account')}>
                        <View style={[styles.flexContainer, styles.mt_dot_1, styles.height_70, styles.mt_20]}>
                            <View style={[styles.pay_row_left, styles.cellfixed, styles.height_70]}>
                                <Image style={{ width: 32, height: 32, paddingHorizontal: 10 }} source={require('../../assets/imgs/e_ye.png')} />
                            </View>
                            <View style={[styles.pay_row_mid, styles.height_70]} >
                                <View style={[styles.pay_row_mid, styles.height_20]} style={{ height: 20 }}>
                                    <Text style={[styles.pay_row_mid_title, styles.color_333, styles.height_20]}>
                                        e学云支付
                                </Text>
                                </View>
                                <View style={[styles.height_20, styles.pay_row_mid]} style={{ height: 20, flexDirection: 'row' }} >
                                    <Text style={[styles.pay_row_mid_title, styles.color_999, styles.ft_14, styles.height_20]}>
                                        可用余额:
                                </Text>
                                    <Text style={[styles.pay_row_mid_title, styles.color_999, styles.ft_14, styles.height_20, styles.pad_left_10]}>
                                        {this.state.remainderSum}
                                    </Text>
                                </View>

                            </View>
                            <View style={[styles.pay_row_right, styles.cellfixed, styles.height_70]}>

                                <Image style={{ width: 24, height: 24, paddingHorizontal: 10, resizeMode: 'cover' }} source={this.checkIconImgs[this.state.PAY_TYPE == 'account' ? "checked" : "unchecked"]} />

                            </View >
                        </View >
                    </TouchableWithoutFeedback>
                    <View style={[styles.card_title]}>
                        <View>
                            <Text style={[styles.color_333]}>其它支付方式</Text>
                        </View>
                    </View >

                    <TouchableWithoutFeedback onPress={() => this._onPressPaySelect('weixin')}>
                        <View style={[styles.flexContainer]} onPress={() => { this._onPressPaySelect('weixin') }}>
                            <View style={[styles.pay_row_left, styles.cellfixed]}>
                                <Image style={{ width: 32, height: 32, paddingHorizontal: 10 }} source={require('../../assets/imgs/weipay.png')} />
                            </View>
                            <View style={styles.pay_row_mid}>
                                <Text style={[styles.pay_row_mid_title, styles.color_333]}>
                                    微信支付
                    </Text>
                            </View>
                            <View style={[styles.pay_row_right, styles.cellfixed]}>

                                <Image style={{ width: 24, height: 24, paddingHorizontal: 10, resizeMode: 'cover' }} source={this.checkIconImgs[this.state.PAY_TYPE == 'weixin' ? "checked" : "unchecked"]} />

                            </View >
                        </View >
                    </TouchableWithoutFeedback>

                    <TouchableWithoutFeedback onPress={() => this._onPressPaySelect('alipay')}>
                        <View style={[styles.flexContainer, styles.mt_1]} onPress={() => { this._onPressPaySelect('alipay') }}>
                            <View style={[styles.pay_row_left, styles.cellfixed]}>
                                <Image style={{ width: 32, height: 32, paddingHorizontal: 10 }} source={require('../../assets/imgs/alipay.png')} />
                            </View>
                            <View style={styles.pay_row_mid}>
                                <Text style={[styles.pay_row_mid_title, styles.color_333]}>
                                    支付宝
                    </Text>
                            </View>
                            <View style={[styles.pay_row_right, styles.cellfixed]}>

                                <Image style={{ width: 24, height: 24, paddingHorizontal: 10, resizeMode: 'cover' }} source={this.checkIconImgs[this.state.PAY_TYPE == 'alipay' ? "checked" : "unchecked"]} />

                            </View >
                        </View >
                    </TouchableWithoutFeedback>

                    <View style={{ justifyContent: 'center', alignItems: 'center', height: 100 }}>
                        <TouchableWithoutFeedback onPress={() => this.onPressSubmit()}>
                            <View style={[styles.submitBtnWrap]}>
                                <Text style={[styles.submitBtn]} >{this.state.btnText}</Text>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>


                    {/* <View style={{ justifyContent: 'center', alignItems: 'center', height: 100 }}>
                    <TouchableWithoutFeedback onPress={() => {
                         var toParams = {
                            fromPaySucess: true
                        };
        
                        this.props.navigation.navigate('DetailLesson', toParams);
                    }}>
                        <View style={[styles.submitBtnWrap]}>
                            <Text style={[styles.submitBtn]} >测试</Text>
                        </View>
                    </TouchableWithoutFeedback>
                </View> */}

                </ScrollView>

            </View >
        );
    }
}

const styles = StyleSheet.create({
    navigatorBar: {
        backgroundColor: '#fff',
    },
    mainContainer: {
        backgroundColor: '#f2f2f2',
        flex: 1
    },
    order_card: {

    },
    order_card_body: {
        backgroundColor: 'white',
        height: 70,
        padding: 15,
        flexDirection: 'row',
        marginBottom: 1
    },
    order_card_body_left: {
        flex: 100,
    },
    order_card_body_right: {
        width: 80,
        alignItems: 'flex-end'
    },
    order_card_footer: {
        height: 50,
        padding: 15,
        justifyContent: 'center',
        backgroundColor: 'white',
        alignItems: 'flex-end'
    },
    amount: {
        justifyContent: 'center',
        color: 'orangered',
        paddingLeft: 20
    },
    order_buy_limit_time: {
        color: 'red',
        height: 24
    },
    order_teacher_wrap: {
        color: '#999',
        height: 24
    },
    order_title_wrap: {
        color: '#555',
        fontSize: 16,
        height: 24,
        // fontWeight: 'bold',
    },
    submitBtnWrap: {
        height: 40,
        lineHeight: 40,
        backgroundColor: '#FF6F26',
        justifyContent: 'center',
        alignItems: 'center',
        width: width * 0.85,
        borderRadius: width < 330 ? 0 : 20,
        marginTop: 10
    },
    submitBtn: {
        color: '#fff',
        // backgroundColor: '#FF6F26',
        fontSize: 14

    },
    height_20: {
        height: 20
    },
    height_70: {
        height: 70
    },
    height_50: {
        height: 50
    },
    color_333: {
        color: '#333'
    },
    color_666: {
        color: '#666'
    },
    color_999: {
        color: '#999'
    },
    ft_14: {
        fontSize: 14
    },
    card_title: {
        backgroundColor: '#f2f2f2',
        height: 46,
        justifyContent: 'center',
        paddingLeft: 20,
        color: '#333'
    },
    mt_1: {
        marginTop: 1
    },
    mt_dot_5: {
        marginTop: 0.5
    },
    pad_left_10: {
        paddingLeft: 10
    },
    flexContainer: {
        // 容器需要添加direction才能变成让子元素flex
        flexDirection: 'row',
        marginTop: 1
    },
    mt_20: {
        marginTop: 20
    },
    pay_row: {
        flex: 1,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center'
    },
    pay_row_mid: {
        flex: 1,
        height: 50,
        backgroundColor: 'white',
        justifyContent: 'center'
    },
    pay_row_mid_title: {
        fontSize: 16,
        marginHorizontal: 0,
        justifyContent: 'center'

    },
    cellfixed: {
        height: 50,
        width: 70,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fefefe'
    },
    buttonContainer: {
        flex: 1,
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        borderTopWidth: 1,
        borderColor: '#eee'
    },
    line: {
        height: 49,
        width: 1,
        backgroundColor: '#eee'
    },
    center: {
        justifyContent: 'center',
        alignItems: 'center'
    },
    inputOutView: {
        paddingHorizontal: 10
    }
});

export default PayScreen;